<template>
  <div class="panel-login">
    <el-form
      v-if="mode === 'setting'"
      :model="formState"
      label-position="top"
      autocomplete="off"
    >
      <el-form-item
        label="请输入访问地址"
        name="url"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <el-input v-model="formState.url" />
      </el-form-item>

      <el-form-item
        label="请输入口令（每个HR有自己的专属口令）"
        name="code"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <el-input v-model="formState.code" />
      </el-form-item>

      <el-form-item style="text-align: right">
        <el-button type="primary" html-type="submit" @click="submitForm">提交</el-button>
      </el-form-item>
    </el-form>

    <div class="msg-card" v-if="mode === 'unset'">
      <img :src="notSetImg" alt="" class="img">
      <div class="text">
        <span>您还未设置</span>
        <el-button type="primary" @click="this.mode = 'setting'">设置</el-button>
      </div>
    </div>

    <div class="msg-card" v-if="mode === 'set_failed'">
      <img :src="setFailedImg" alt="" class="img">
      <div class="text">
        <span style="color: red;">口令不正确或已过期</span>
        <el-button type="primary" @click="this.mode = 'setting'">重新设置</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getFromStorage } from '../lib'

const notSetImg = chrome.runtime.getURL('assets/not_set@2x.png')
const setFailedImg = chrome.runtime.getURL('assets/setup_failed@2x.png')


export default {
  props: {
    onPanelChange: Function
  },
  data(){
    return {
      notSetImg,
      setFailedImg,
      mode: 'setting',
      formState: {
        url: '',
        code: '',
      },
    }
  },
  methods: {
    submitForm(){
      if(!this.formState.url){
        this.$this.$message.error('请输入访问地址')
        return
      }
      if(!this.formState.code){
        this.$message.error('请输入口令')
        return
      }
      const callback = this.onPanelChange
      const completeUrl = `${this.formState.url}/hrms/assistant/login`
      this.axios.post(completeUrl, {
        code: this.formState.code,
      }).then((res) => {
        chrome.storage.sync.set({HRMS_LOGIN_HOST: this.formState.url})
        chrome.storage.sync.set({HRMS_LOGIN_CODE: this.formState.code})
        chrome.storage.sync.set({HRMS_TOKEN: res.token, HRMS_USERINFO: res.userInfo}, function() {
          chrome.storage.sync.set({HRMS_PAGE: 'WORK'})
          callback('WORK')
          this.$message.success('设置成功')
        })
      }).catch(() => {
        this.mode = 'set_failed'
      })
    },
    getPopupContainer(triggerNode){return triggerNode.parentNode}
  },
  async created() {
    const loginHost = (await getFromStorage('HRMS_LOGIN_HOST')) || ''
    const loginCode = (await getFromStorage('HRMS_LOGIN_CODE')) || ''
    this.formState.url = loginHost
    this.formState.code = loginCode
  },
}

</script>

<style lang="less" scoped>
@import "./styles/panel-login.less";
</style>